#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart, MIMEBase
from email.utils import parseaddr, formataddr
import smtplib

# 我们编写了一个函数_format_addr()来格式化一个邮件地址。注意不能简单地传入name <addr@example.com>，
# 因为如果包含中文，需要通过Header对象进行编码。
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

# 注意"To"接收的是str不是list，不同的收件人中间用,隔开，所以这里创建函数来处理多个收件人的情况
def get_formated_sendto(sendto_li):
    formated_sendto = ""
    for listmember in sendto_li:
        member_name = listmember[:listmember.index('@')]
        formated_sendto = formated_sendto + _format_addr("%s<%s>" % (member_name, listmember)) + ","
    return formated_sendto

# 基本信息
smtpserver = "smtp.126.com"
username = 'archon2000@126.com'
password = 'xy15306189918'
sender = username
# receiver 必须是一个列表
receiver = ['174324158@qq.com', 'archon2000@126.com', 'xiaoyao@vmware.com']
subject = 'Python email test'
with open(r"C:\Downloads\TestResult_2018-02-12_17-25-57.html", 'rb') as r:
    mailbody = r.read()

# 创建MIMEMultipart对象
msg = MIMEMultipart()
msg["From"] = _format_addr("archon2000<%s>" % sender)
msg["To"] = get_formated_sendto(receiver)
msg["Subject"] = Header(subject, 'utf-8').encode()
# 添加正文
msg.attach(MIMEText(mailbody, 'html','utf-8'))
# 添加附件就是加上一个MIMEBase，从本地读取一个图片:
with open(r'C:\Downloads\TestResult_2018-02-12_14-28-37.html', 'rb') as f:
    mime = MIMEBase('html', 'html', filename='TestResult_2018-02-12_14-28-37.html')
    # 加上必要的头部信息
    mime.add_header('Content-Disposition', 'attachment', filename='TestResult_2018-02-12_14-28-37.html')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    # 读取附件内容
    mime.set_payload(f.read())
    # 用Base64编码:
    encoders.encode_base64(mime)
    # 添加到MIMEMultipart:
    msg.attach(mime)

# 发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
# sendmail方法发送人是一个列表，邮件正文是str，所以用as_string()方法把MIME对象变成str
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

